import React, {
  Fragment,
  memo,
  useCallback,
  useContext,
  useEffect,
  useState,
} from 'react';
import Horizon from '@/baseUI/horizon-item';
import { categoryTypes, alphaTypes } from '@/api/local_data';
import { NavContainer, ListContainer, List, ListItem } from './style';
import Scroll from '@/baseUI/scroll';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { actionCreators } from './store';
import { getCateorySingerListAction } from './store/actionCreators';
// 首先引入
import LazyLoad, { forceCheck } from 'react-lazyload';
import Loading from '@/baseUI/loading';
import { CategoryAlphaContext, CHANGE_ALPHA, CHANGE_CATEGORY } from './data';
import { renderRoutes } from 'react-router-config';
const {
  getHotSingerListAction,
  changePageCountAction,
  changeEnterLoadingAction,
  changePullUpLoadingAction,
  changePullDownLoadingAction,
  refreshGetMoreCategorySingerListAction,
  refreshGetMoreHotSingerListAction,
} = actionCreators;
export default memo(function Singers(props) {
  const {
    singerList,
    enterLoading,
    pullDownLoading,
    pageCount,
    pullUpLoading,
  } = useSelector(
    (state) => ({
      singerList: state.singers.singerList,
      enterLoading: state.singers.enterLoading,
      pullUpLoading: state.singers.pullUpLoading,
      pullDownLoading: state.singers.pullDownLoading,
      pageCount: state.singers.pageCount,
    }),
    shallowEqual
  );
  const dispatch = useDispatch();

  // const [category, setCategory] = useState(null);
  // const [alpha, setAlpha] = useState(null);

  const { data, dataDispatch } = useContext(CategoryAlphaContext);
  const { category, alpha } = data;
  // 组件第一次渲染时 获取热门歌手数据
  useEffect(() => {
    dispatch(getHotSingerListAction());
  }, [dispatch]);
  //  category或者字母发生改变时 请求数据
  const updateDispatch = useCallback(
    (category, alpha) => {
      dispatch(changePageCountAction(0)); //由于改变了分类，所以pageCount清零
      dispatch(changeEnterLoadingAction(true)); //loading，现在实现控制逻辑，
      dispatch(getCateorySingerListAction(category, alpha));
    },
    [dispatch]
  );
  // 触发改变 category
  const handleUpdateCategory = useCallback(
    (val) => {
      // setCategory((i) => val);
      dataDispatch({ type: CHANGE_CATEGORY, category: val });
      // 当点击category，category发生变化时，请求类别歌手数据
      updateDispatch(val, alpha);
    },
    [alpha, updateDispatch, dataDispatch]
  );
  // 触发改变 alpha字母
  const handleUpdateAlpha = useCallback(
    (val) => {
      // setAlpha((i) => val);
      dataDispatch({ type: CHANGE_ALPHA, alpha: val });
      // 当alpha发生变化时 alpha发生变化时，请求类别歌手数据
      updateDispatch(category, val);
    },
    [category, updateDispatch, dataDispatch]
  );
  // 滑到最底部刷新获取更多数据
  const pullUpRefreshDispatch = useCallback(
    (category, alpha, hot, count) => {
      // 获取时显示加载的图标
      dispatch(changePullUpLoadingAction(true));
      //  获取下一页
      dispatch(changePageCountAction(count + 1));
      // 判断是否是hot热门
      if (hot) {
        // 获取更多热门歌手的数据
        dispatch(refreshGetMoreHotSingerListAction());
      } else {
        // 获取更多类别歌手的数据
        dispatch(refreshGetMoreCategorySingerListAction(category, alpha));
      }
    },
    [dispatch]
  );
  //在顶部下拉刷新
  const pullDownRefreshDispatch = useCallback(
    (category, alpha) => {
      // 显示加载的图标
      dispatch(changePullDownLoadingAction(true));
      // 把count重置为0
      dispatch(changePageCountAction(0)); //属于重新获取数据
      if (category === null && alpha === null) {
        // 如果都没有选择则自动请求热门歌手列表
        dispatch(getHotSingerListAction());
      } else {
        //请求类别歌手列表的数据
        dispatch(getCateorySingerListAction(category, alpha));
      }
    },
    [dispatch]
  );
  const handlePullUp = useCallback(() => {
    pullUpRefreshDispatch(category, alpha, category === null, pageCount);
  }, [category, alpha, pageCount, pullUpRefreshDispatch]);
  const handlePullDown = useCallback(() => {
    pullDownRefreshDispatch(category, alpha);
  }, [category, alpha, pullDownRefreshDispatch]);
  const enterDetail = (id) => {
    props.history.push(`/singers/${id}`);
  };
  const renderSingerList = () => {
    return (
      <List>
        {singerList.map((item, index) => {
          return (
            <ListItem
              key={item.accountId + '' + index}
              onClick={() => {
                enterDetail(item.id);
              }}
            >
              <div className="img_wrapper">
                <LazyLoad
                  placeholder={
                    <img
                      width="100%"
                      height="100%"
                      src={require('./singer.png').default}
                      alt="music"
                    />
                  }
                >
                  <img
                    src={`${item.picUrl}?param=300x300`}
                    width="100%"
                    height="100%"
                    alt="music"
                  />
                </LazyLoad>
              </div>
              <span className="name">{item.name}</span>
            </ListItem>
          );
        })}
      </List>
    );
  };
  return (
    <Fragment>
      {/*  外部容器限定宽度 */}
      <NavContainer>
        {/*  内部宽度没有进行相应的计算，始终为屏幕宽度 */}
        <Horizon
          list={categoryTypes}
          title={'分类（默认热门）'}
          handleClick={handleUpdateCategory}
          oldVal={category && category.key}
        />
        <Horizon
          list={alphaTypes}
          title={'首字母:'}
          handleClick={handleUpdateAlpha}
          oldVal={alpha && alpha.key}
        />
      </NavContainer>
      {/* 外部的wrapper */}
      <ListContainer>
        <Scroll
          pullUp={handlePullUp}
          pullDown={handlePullDown}
          pullUpLoading={pullUpLoading}
          pullDownLoading={pullDownLoading}
          onScroll={forceCheck}
        >
          {renderSingerList()}
        </Scroll>

        {enterLoading && <Loading show={enterLoading}></Loading>}
      </ListContainer>
      {renderRoutes(props.route.routes)}
    </Fragment>
  );
});
